import axios from "axios";
import { ElMessage } from "element-plus";
import useStore from '@/store';
import router from '@/router';
const service = axios.create({
	baseURL: "http://127.0.0.1:5200",
	timeout: 10000,
});
// 请求拦截器
service.interceptors.request.use(
	(config) => {
		const { user } = useStore();
		if (user.token) {
			config.headers.Authorization = user.token;
		}
		return config;
	},
	(error) => {
		Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(response) => {
		const { user } = useStore();
		// code值为失败执行的操作
		if (response.data.code !== 200) {
			ElMessage.error(response.data.message);
			// 单点登录打断退出
			if (response.data.code == 1011) {
				user.Logout();
				router.push({
					path: '/login',
					query: { returnUrl: router.currentRoute.value.fullPath },
				});
			}
			// 抛出异常
			throw new Error(response.data.message);
		}
		// 响应成功
		return response.data.data;
	},
	(error) => {
		if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
			ElMessage.error('请求超时,请稍后重试');
			throw new Error("请求超时,请稍后重试");
		} else {
			error.data.message = "连接到服务器失败";
			ElMessage.error(error.data.message);
		}
		return Promise.reject(error);
	}
);

export default service;
